package com.whut.transportation;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.transportation.entity.Message;
import com.whut.transportation.entity.TaskInfo;
import com.whut.transportation.entity.TransInfo;
import com.whut.transportation.network.HttpManager;
import com.whut.transportation.network.HttpRequestVo;
import com.whut.transportation.parser.JSONParser;
import com.whut.transportation.ui.BaseActivity;
import com.whut.transportation.utils.Constant;
import com.whut.transportation.utils.MyLog;
import com.whut.transportation.wheel.StrericWheelAdapter;
import com.whut.transportation.wheel.WheelView;
/**
 * 卸车信息查看，处理
 * @author yuliyan
 */
public class UnloadDetailActivity extends BaseActivity {
	
	private TextView unload_number;
	private TextView unload_trainNum;
	private TextView unload_train;
	private TextView unload_station;
	private TextView unload_goods;
	private TextView unload_name;
	private TextView unload_weight;
	private TextView unload_gudao;
	private TextView unload_time;
	private Button unload_xiugai;
	
	private Button auto_unload_beginTime;
	private Button auto_unload_beginTime_submit;
	private EditText unload_begin_date;
	private EditText unload_begin_time_pre;
	private EditText unload_begin_time_last;
	
	private LinearLayout unload_line6;
	private Button auto_unload_endTime;
	private Button auto_unload_endTime_submit;
	private EditText unload_end_date;
	private EditText unload_end_time_pre;
	private EditText unload_end_time_last;
	
	private LinearLayout unload_line7;
	
	private EditText unload_bu_number;
	private Button unload_submit;
	
	private TransInfo transinfo;
	private TaskInfo taskInfo;
	
	private SharedPreferences preferences;//偏好信息
	private boolean flag = false;//
	private int gudaoId;
	private int minYear = 1970;  //最小年份
	private int fontSize = 13; 	 //字体大小
	//private WheelView yearWheel,monthWheel,dayWheel,hourWheel,minuteWheel,secondWheel;
	private WheelView yearWheel,monthWheel,dayWheel,hourWheel,minuteWheel;
	public static String[] yearContent=null;
	public static String[] monthContent=null;
	public static String[] dayContent=null;
	public static String[] hourContent = null;
	public static String[] minuteContent=null;
	
	@Override
	protected void loadViewLayout() {
		setContentView(R.layout.activity_unload_detail);
		Intent intent = getIntent();
		transinfo = (TransInfo)intent.getSerializableExtra("transinfo");
		preferences=getSharedPreferences("userId", Context.MODE_PRIVATE);
		setTitleBarView(true, transinfo.getTrainNumber()+transinfo.getTrain()+"卸车", -1, true);
		initContent();
	}
	@Override
	protected void findViewById() {
		unload_number = (TextView) findViewById(R.id.unload_number);
		unload_trainNum = (TextView) findViewById(R.id.unload_trainNum);
		unload_train = (TextView) findViewById(R.id.unload_train);
		unload_station = (TextView) findViewById(R.id.unload_station);
		unload_goods = (TextView) findViewById(R.id.unload_goods);
		unload_name = (TextView) findViewById(R.id.unload_name);
		unload_weight = (TextView) findViewById(R.id.unload_weight);
		unload_gudao = (TextView) findViewById(R.id.unload_gudao);
		unload_time = (TextView) findViewById(R.id.unload_time);
		unload_xiugai = (Button) findViewById(R.id.unload_xiugai);
		
		auto_unload_beginTime = (Button) findViewById(R.id.auto_unload_beginTime);
		auto_unload_beginTime_submit = (Button) findViewById(R.id.auto_unload_beginTime_submit);
		unload_begin_date = (EditText) findViewById(R.id.unload_begin_date);
		unload_begin_time_pre = (EditText) findViewById(R.id.unload_begin_time_pre);
		unload_begin_time_last = (EditText) findViewById(R.id.unload_begin_time_last);
		
		unload_line6 = (LinearLayout) findViewById(R.id.unload_line6);
		auto_unload_endTime = (Button) findViewById(R.id.auto_unload_endTime);
		auto_unload_endTime_submit = (Button) findViewById(R.id.auto_unload_endTime_submit);
		unload_end_date = (EditText) findViewById(R.id.unload_end_date);
		unload_end_time_pre = (EditText) findViewById(R.id.unload_end_time_pre);
		unload_end_time_last = (EditText) findViewById(R.id.unload_end_time_last);
		
		unload_line7 = (LinearLayout) findViewById(R.id.unload_line7);
		unload_bu_number = (EditText) findViewById(R.id.unload_bu_number);
		unload_submit = (Button) findViewById(R.id.unload_submit);
		
		unload_submit = (Button) findViewById(R.id.unload_submit);
	}

	@Override
	protected void afterFindViewId() {
		unload_number.setText(unload_number.getText()+transinfo.getNumber());
		unload_trainNum.setText(unload_trainNum.getText()+transinfo.getTrainNumber());
		unload_train.setText(unload_train.getText()+transinfo.getTrain());
		unload_station.setText(unload_station.getText()+transinfo.getStation());
		unload_goods.setText(unload_goods.getText()+transinfo.getGoods());
		unload_name.setText(unload_name.getText()+transinfo.getName());
		unload_weight.setText(unload_weight.getText()+String.valueOf(transinfo.getWeight()+"t"));
		unload_gudao.setText(unload_gudao.getText()+String.valueOf(transinfo.getGudao()));
		
	}

	@Override
	protected void processLogic() {
		//进入页面时查询卸车记录信息，如果已有卸车信息，则查询出来显示，如果卸车信息为空，则提示下次操需要向卸车记录表中新增记录
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.Find_TASK_SCK_INFO;
		vo.context = mContext;
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("id", transinfo.getId());
		vo.requestDataMap = req;
		vo.parser = new JSONParser(TaskInfo.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
						
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						taskInfo = (TaskInfo) paramObject.get("result");
						//message卸车表中是否存在记录，0表示没有记录，1存在一条记录，但这条记录中没有结束时间，只有开始时间，2表示这条记录中开始时间和结束时间都有
						//不等于0表示存在记录
						if(taskInfo.getMessage() != 0){
							unload_line6.setVisibility(View.VISIBLE);
							auto_unload_beginTime_submit.setVisibility(View.VISIBLE);
							String begintime = taskInfo.getBegintime().trim();
							String[] s1 = begintime.split(" ");
							unload_begin_date.setText(s1[0]);
							String[] s2 = s1[1].split(":");
							unload_begin_time_pre.setText(s2[0]);
							unload_begin_time_last.setText(s2[1]);
							
							//unload_time.setText(unload_time.getText()+taskInfo.getIntime());
						} 
						//等于2表示记录中结束时间已经存在
						if(taskInfo.getMessage() == 2){
							auto_unload_endTime_submit.setVisibility(View.VISIBLE);
							unload_submit.setVisibility(View.VISIBLE);
							String endtime = taskInfo.getEndtime().trim();
							String s1[] = endtime.split(" ");
							unload_end_date.setText(s1[0]);
							String s2[] = s1[1].split(":");
							unload_end_time_pre.setText(s2[0]);
							unload_end_time_last.setText(s2[1]);
							
							//unload_time.setText(unload_time.getText()+taskInfo.getIntime());
						}
						
						if (taskInfo.getIntime()!=null) {
							unload_time.setText(taskInfo.getIntime());
						} else {
							unload_time.setText(transinfo.getTime());
						}
					}

					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
		
	}
	@Override
	protected void setListener() {
		unload_submit.setOnClickListener(this);
		auto_unload_beginTime.setOnClickListener(this);
		auto_unload_beginTime_submit.setOnClickListener(this);
		auto_unload_endTime.setOnClickListener(this);
		auto_unload_endTime_submit.setOnClickListener(this);
		unload_xiugai.setOnClickListener(this);
	}
	@Override
	protected void getDataAgain() {
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.unload_submit:
			submitUnload();
			break;
		case R.id.auto_unload_beginTime: //自动生成
			//第一个自动生成时间的按钮
			show1();
			break;
		case R.id.auto_unload_beginTime_submit://下一步
			//第一个下一步按钮
			show2();
			break;
		case R.id.auto_unload_endTime://自动生成
			//第二自动生成时间的按钮
			show3();
			break;
		case R.id.auto_unload_endTime_submit://下一步
			//第二个下一步按钮
			show4();
		case R.id.unload_xiugai:
			//修改时间
			show5();
		default:
			break;
		}
		super.onClick(v);
	}
	private void show5() {
		View view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.time_picker, null); 
		
		Calendar calendar = Calendar.getInstance();
	    int curYear = calendar.get(Calendar.YEAR);
        int curMonth= calendar.get(Calendar.MONTH)+1;
        int curDay = calendar.get(Calendar.DAY_OF_MONTH);
        int curHour = calendar.get(Calendar.HOUR_OF_DAY);
        int curMinute = calendar.get(Calendar.MINUTE);
 	    
	    yearWheel = (WheelView)view.findViewById(R.id.yearwheel);
	    monthWheel = (WheelView)view.findViewById(R.id.monthwheel);
	    dayWheel = (WheelView)view.findViewById(R.id.daywheel);
	 /*   hourWheel = (WheelView)view.findViewById(R.id.hourwheel);
	    minuteWheel = (WheelView)view.findViewById(R.id.minutewheel);*/
	   
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  
        builder.setView(view); 
        
        yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
	 	yearWheel.setCurrentItem(curYear-2013);
	    yearWheel.setCyclic(true);
	    yearWheel.setInterpolator(new AnticipateOvershootInterpolator());
        
 
        monthWheel.setAdapter(new StrericWheelAdapter(monthContent));
       
        monthWheel.setCurrentItem(curMonth-1);
     
        monthWheel.setCyclic(true);
        monthWheel.setInterpolator(new AnticipateOvershootInterpolator());
        
        dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
        dayWheel.setCurrentItem(curDay-1);
        dayWheel.setCyclic(true);
        dayWheel.setInterpolator(new AnticipateOvershootInterpolator());
        
        hourWheel.setAdapter(new StrericWheelAdapter(hourContent));
        hourWheel.setCurrentItem(curHour);
        hourWheel.setCyclic(true);
        hourWheel.setInterpolator(new AnticipateOvershootInterpolator());
        
        minuteWheel.setAdapter(new StrericWheelAdapter(minuteContent));
        minuteWheel.setCurrentItem(curMinute);
        minuteWheel.setCyclic(true);
        minuteWheel.setInterpolator(new AnticipateOvershootInterpolator());
        
        builder.setTitle("选取时间");  
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  
        	@Override  
        	public void onClick(DialogInterface dialog, int which) {  
        		StringBuffer sb = new StringBuffer();  
        		sb.append(yearWheel.getCurrentItemValue()).append("-")
        		.append(monthWheel.getCurrentItemValue()).append("-")
        		.append(dayWheel.getCurrentItemValue());
        		sb.append(" ");  
        		sb.append(hourWheel.getCurrentItemValue())  
        		.append(":").append(minuteWheel.getCurrentItemValue());
        		unload_time.setText(sb.toString());
        		dialog.cancel();  
        	}  
        });  
   
        builder.show();
	}
	/**
	 * 更新结束时间
	 */
	private void show4() {
		String beginTime = unload_begin_date.getText().toString().trim()+" "+unload_begin_time_pre.getText().toString().trim()
				+":"+unload_begin_time_last.getText().toString().trim();
		String endTime = unload_end_date.getText().toString().trim()+" "+unload_end_time_pre.getText().toString().trim()
				+":"+unload_begin_time_last.getText().toString().trim();
		String in_time = unload_time.getText().toString();
		updateTaskInfo(beginTime,endTime,in_time,null);
		
	}
	/**
	 * 自动生成结束时间
	 */
	private void show3() {
		Date date = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("HH");
		SimpleDateFormat df2 = new SimpleDateFormat("mm");
		SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");
		String hh = df1.format(date);
		String mm = df2.format(date);
		String d = df3.format(date);
		unload_end_time_pre.setText(hh);
		unload_end_time_last.setText(mm);
		unload_end_date.setText(d);
		//auto_unload_endTime_submit.setVisibility(View.VISIBLE);
		unload_submit.setVisibility(View.VISIBLE);
	}
	/**
	 * 判断卸车表是否存在记录，不存在则新增，存在则更新
	 * flag判断按钮是否点击过，第一次点击表示，需要新增记录
	 */
	private void show2() {
		String beginTime = unload_begin_date.getText().toString().trim()+" "+unload_begin_time_pre.getText().toString().trim()
				+":"+unload_begin_time_last.getText().toString().trim();
		String in_time = unload_time.getText().toString();
		updateTaskInfo(beginTime,null,in_time,null);
		unload_line6.setVisibility(View.VISIBLE);
		//unload_submit.setVisibility(View.VISIBLE);
	}
	/**
	 * 自动生成开始时间
	 */
	private void show1() {
		Date date = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("HH");
		SimpleDateFormat df2 = new SimpleDateFormat("mm");
		SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");
		String hh = df1.format(date);
		String mm = df2.format(date);
		String d = df3.format(date);
		unload_begin_time_pre.setText(hh);
		unload_begin_time_last.setText(mm);
		unload_begin_date.setText(d);
		auto_unload_beginTime_submit.setVisibility(View.VISIBLE);
	}
	/**
	 * 提交所有信息
	 */
	private void submitUnload() {
		
		 AlertDialog.Builder builder = new AlertDialog.Builder(UnloadDetailActivity.this);
		 builder.setTitle("提醒");
		 builder.setMessage("确定提交吗？");
		 builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {

				String beginTime = unload_begin_date.getText().toString().trim()+" "+unload_begin_time_pre.getText().toString().trim()
						+":"+unload_begin_time_last.getText().toString().trim();
				String endTime = unload_end_date.getText().toString().trim()+" "+unload_end_time_pre.getText().toString().trim()
						+":"+unload_begin_time_last.getText().toString().trim();
				String bu_number = unload_bu_number.getText().toString();
				//如果送入时间已修改，则在这要用新的时间替代，需要查询得到****
				String in_time = unload_time.getText().toString();
				if(bu_number.length()<=0)
					Toast.makeText(mContext, "施封蓬布号不能为空", Toast.LENGTH_SHORT);
				else 
					updateTaskInfo(beginTime, endTime, in_time, bu_number);
			}
		 });
		 builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
             @Override
             public void onClick(DialogInterface dialog, int which)
             {
             }
         });
		 builder.show();
	}
	/**
	 * 更新TaskInfo
	 * @param begin 开始时间
	 * @param end 结束时间
	 * @param in_time 送入时间
	 * @param bu_number 施封篷布号
	 */
	private void updateTaskInfo(String begin,String end,String in_time,String bu_number) {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.UPDATE_TASK_SCK_INFO;
		vo.context = mContext;
		vo.parser = new JSONParser(Message.class);
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("account", preferences.getString("account", null));
		req.put("id", transinfo.getId());
		req.put("taskStyle", String.valueOf(transinfo.getType()));
		req.put("shunhao", transinfo.getNumber());
		req.put("taskInfo.timeStart", begin);
		taskInfo.setBegintime(begin);
		if(null != end){
			req.put("taskInfo.timeEnd", end);
			taskInfo.setEndtime(end);
		}
		if(null != in_time){
			req.put("taskInfo.timeIn", in_time);
			taskInfo.setIntime(in_time);
		}
		
		vo.requestDataMap = req;
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
				@Override
				public void onStart() {
					showProgressDialog(getResources().getString(
							R.string.loading_content));
				}
				@Override
				public void onFailed() {
					showNetErrorDialog();
				}
				@Override
				public void processData(
						HashMap<String, Object> paramObject,
						boolean paramBoolean) {
					Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
					Message message = (Message) paramObject.get("result");
					if(message.getMessage() == 1){
						Intent intent = new Intent(UnloadDetailActivity.this, SuccessActivity.class);
						intent.putExtra("transinfo", transinfo);
						intent.putExtra("taskInfo", taskInfo);
						startActivity(intent);
					}
				}
				@Override
				public void onFinish() {
					closeProgressDialog();
				}
		});
	}
	
	 public void initContent()
		{
			yearContent = new String[10];
			for(int i=0;i<10;i++)
				yearContent[i] = String.valueOf(i+2013);
			
			monthContent = new String[12];
			for(int i=0;i<12;i++)
			{
				monthContent[i]= String.valueOf(i+1);
				if(monthContent[i].length()<2)
		        {
					monthContent[i] = "0"+monthContent[i];
		        }
			}
				
			dayContent = new String[31];
			for(int i=0;i<31;i++)
			{
				dayContent[i]=String.valueOf(i+1);
				if(dayContent[i].length()<2)
		        {
					dayContent[i] = "0"+dayContent[i];
		        }
			}	
			hourContent = new String[24];
			for(int i=0;i<24;i++)
			{
				hourContent[i]= String.valueOf(i);
				if(hourContent[i].length()<2)
		        {
					hourContent[i] = "0"+hourContent[i];
		        }
			}
				
			minuteContent = new String[60];
			for(int i=0;i<60;i++)
			{
				minuteContent[i]=String.valueOf(i);
				if(minuteContent[i].length()<2)
		        {
					minuteContent[i] = "0"+minuteContent[i];
		        }
			}
		}
}
